package cjyyp.day02;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class 交替输出abc {
    static ReentrantLock reentrantLock=new ReentrantLock();
    //线程1休息房间
    static Condition condition1=reentrantLock.newCondition();
    //线程2休息房间
    static Condition condition2=reentrantLock.newCondition();
    //线程3休息房间
    static Condition condition3=reentrantLock.newCondition();
    static   int count1=1;
    static   int count2=1;
    static   int count3=1;
    public static void main(String[] args) throws InterruptedException {
        Thread t1=new Thread(new Runnable() {
            @Override
            public void run() {
                reentrantLock.lock();
                while (count1<=3){
                    System.out.print("a");
                    count1++;
                    try {
                        condition2.signal();
                        condition1.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                condition2.signal();
                reentrantLock.unlock();
            }
        });
        Thread t2=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    t1.join(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock.lock();
                while (count2<=3){
                    System.out.print("b");
                    count2++;
                    try {
                        condition3.signal();
                        condition2.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                condition3.signal();
                reentrantLock.unlock();
            }
        });
        Thread t3=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    t2.join(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock.lock();
                while (count3<=3){
                    System.out.print("c");
                    count3++;
                    try {
                        condition1.signal();
                        condition3.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                reentrantLock.unlock();
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
